<template>
  <el-button type="primary" :loading="isPublishing" class="publish-btn ml-tiny" @click="handlePublish">
    发布
  </el-button>

  <PublishPage
    :formId="formId"
    :setting="true"
    :visible="formsPublishVisible"
    @on-close-codify="onClose"
  />
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { useStore } from 'vuex'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/src/message.scss'

import { publishForm, update as updateForm } from '@/management/api/dataform'
import { showLogicEngine } from '@/management/hooks/useShowLogicEngine'
import PublishPage from '@/management/pages/publish/PublishPage.vue'
import buildData from './buildData'

const isPublishing = ref<boolean>(false)
const store = useStore()
// const router = useRouter()
const route = useRoute()

const formsPublishVisible = ref(false)
const formId: any = route.params.id || ''

const updateLogicConf = () => {
  if (
    showLogicEngine.value &&
    showLogicEngine.value.rules &&
    showLogicEngine.value.rules.length !== 0
  ) {
    showLogicEngine.value.validateSchema()
    const showLogicConf = showLogicEngine.value.toJson()
    // 更新逻辑配置
    store.dispatch('editform/changeSchema', { key: 'logicConf', value: { showLogicConf } })
  }
}
const onClose = () => {
  formsPublishVisible.value = false
}

const handlePublish = async () => {
  if (isPublishing.value) {
    return
  }

  isPublishing.value = true
  
  try {
    updateLogicConf()
  } catch (err) {
    isPublishing.value = false
    ElMessage.error('请检查逻辑配置是否有误')
    return
  }

  const saveData = buildData(store.state.editform.schema)
  if (!saveData.formId) {
    isPublishing.value = false
    ElMessage.error('未获取到活动id')
    return
  }
  setTimeout(async () => {
    try {
      const saveRes: any = await updateForm(saveData)
      if (saveRes?.serverResult?.resultCode !== '200') {
        isPublishing.value = false
        ElMessage.error(saveRes?.serverResult?.resultMessage || '活动保存失败')
        return
      } else if (saveRes?.result?.dataFormAttributeList) {
        store.dispatch('editform/updataQuestionList', saveRes?.result?.dataFormAttributeList || [])
      }

      const publishRes: any = await publishForm({ formId: saveData.formId })
      if (publishRes?.serverResult?.resultCode === '200') {
        ElMessage.success('发布成功')
        store.dispatch('editform/getSchemaFromRemote')

        formsPublishVisible.value = true
      } else {
        ElMessage.error(`发布失败 ${publishRes?.serverResult?.resultMessage}`)
      }
    } catch (err) {
      console.log(err)
      ElMessage.error(`发布失败`)
    } finally {
      isPublishing.value = false
    }
  }, 1000)
}
</script>
<style lang="scss" scoped>
.publish-btn {
  width: 100px;
  font-size: 14px;
  height: 36px;
  line-height: 36px;
  padding: 0;
}
</style>
